﻿using MySql.Data.MySqlClient;
using System;
using System.Configuration;
using System.Windows.Forms;

namespace TubeBurstAnalysis
{
    public partial class FormRegister : Form
    {
        public FormRegister()
        {
            InitializeComponent();
            textBox2.PasswordChar = '*';
            textBox3.PasswordChar = '*';
            StartPosition = FormStartPosition.CenterScreen;//窗体居中
            Show();
            textBox1.Focus();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            //注册
            string userName = textBox1.Text;
            string userPassword = textBox2.Text;
            string password2 = textBox3.Text;

            if (userName.Equals("") || userPassword.Equals(""))
            {
                MessageBox.Show("用户名或密码不能为空！");
            }

            if (!password2.Equals(userPassword))
            {
                MessageBox.Show("两次输入密码不一致，请重新输入！");
                textBox3.Clear();
            }
            else
            {
                //获取数据库连接
                string strcon = ConfigurationManager.ConnectionStrings["connString"].ToString();
                MySqlConnection con = new MySqlConnection(strcon);
                try
                {
                    //2. 打开数据库
                    con.Open();
                    //3.检查用户名冲突
                    string sqlSearch = "select count(*) from user where user_name='" + userName + "'";
                    MySqlCommand com1 = new MySqlCommand(sqlSearch, con);

                    if (Convert.ToInt32(com1.ExecuteScalar()) != 0)
                    {
                        MessageBox.Show("用户名已被占用,请重新输入用户名");
                        return;
                    }
                    //4.插入数据
                    string sqlSel = "insert into user(user_name, password) value ('" + userName +
                        "','" + userPassword + "')";
                    MySqlCommand com2 = new MySqlCommand(sqlSel, con);
                    com2.ExecuteNonQuery();
                    MessageBox.Show("注册成功");
                    Hide();

                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message + ex.StackTrace);
                }

            }
        }
    }
}
